<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户角色管理</title>
    <script src="/js/vue.js"></script>
    <link type="text/css" rel="stylesheet" href="/css/index.css">
    <script src="/js/index.js"></script>
    <script src="/js/axios.min.js"></script>
    <style>
        .search-box {
            margin-bottom: 20px;
            padding: 15px;
            background: #f5f7fa;
            border-radius: 4px;
        }
        .role-checkbox-group {
            max-height: 300px;
            overflow-y: auto;
            padding: 10px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
        }
        .el-checkbox {
            margin-right: 15px;
            margin-bottom: 10px;
        }
        .pagination-container {
            margin-top: 20px;
            text-align: right;
        }
        /* 自定义图标样式 */
        .custom-info-icon {
            display: inline-block;
            width: 16px;
            height: 16px;
            line-height: 16px;
            text-align: center;
            border-radius: 50%;
            background-color: #909399;
            color: #fff;
            font-size: 12px;
            margin-left: 5px;
            cursor: help;
        }
        /* 角色项样式 */
        .role-item {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }
        .role-name {
            margin-right: 5px;
        }
        /* 对话框样式优化 */
        .el-dialog__body {
            padding: 20px;
        }
        .user-info {
            margin-bottom: 20px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 4px;
        }
        .user-info-item {
            margin-bottom: 10px;
            color: #606266;
        }
        .user-info-label {
            font-weight: bold;
            margin-right: 10px;
        }
    </style>
</head>
<body>
<div id="app">
    <el-card class="box-card">
        <div slot="header" class="clearfix">
            <span>用户角色管理</span>
        </div>

        <!-- 搜索框 -->
        <div class="search-box">
            <el-form :inline="true" :model="searchForm" size="small">
                <el-form-item label="用户名">
                    <el-input v-model="searchForm.user_name" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="真实姓名">
                    <el-input v-model="searchForm.real_name" placeholder="请输入真实姓名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 用户表格 -->
        <el-table :data="userList" border style="width: 100%" v-loading="loading">
            <el-table-column prop="user_id" label="用户ID" width="80" align="center"></el-table-column>
            <el-table-column prop="user_name" label="用户名"></el-table-column>
            <el-table-column prop="real_name" label="真实姓名"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            <el-table-column prop="phonenumber" label="手机号"></el-table-column>
            <el-table-column label="状态" width="80" align="center">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
                        {{ scope.row.status === '0' ? '正常' : '停用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="handleAssignRole(scope.row)">分配角色</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageNum"
                :page-sizes="[10, 20, 30, 50]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>

        <!-- 角色分配对话框 -->
        <el-dialog title="分配角色" :visible.sync="dialogVisible" width="500px">
            <div class="user-info">
                <div class="user-info-item">
                    <span class="user-info-label">用户名：</span>
                    <span>{{ currentUser.user_name }}</span>
                </div>
                <div class="user-info-item">
                    <span class="user-info-label">真实姓名：</span>
                    <span>{{ currentUser.real_name }}</span>
                </div>
            </div>
            <el-form :model="roleForm" label-width="80px">
                <el-form-item label="角色">
                    <div class="role-checkbox-group">
                        <el-checkbox-group v-model="roleForm.roleIds">
                            <div v-for="role in roleList" :key="role.roleId" class="role-item">
                                <el-checkbox :label="role.roleId">
                                    <span class="role-name">{{ role.roleName }}</span>
                                    <span v-if="role.remark" class="custom-info-icon" :title="role.remark">?</span>
                                </el-checkbox>
                            </div>
                        </el-checkbox-group>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveUserRoles" :loading="saveLoading">确 定</el-button>
            </div>
        </el-dialog>
    </el-card>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                // 搜索表单
                searchForm: {
                    user_name: '',
                    real_name: ''
                },
                // 用户列表数据
                userList: [],
                // 角色列表数据
                roleList: [],
                // 分页参数
                pageNum: 1,
                pageSize: 10,
                total: 0,
                // 加载状态
                loading: false,
                saveLoading: false,
                // 对话框显示状态
                dialogVisible: false,
                // 当前选中的用户
                currentUser: {},
                // 角色表单
                roleForm: {
                    roleIds: []
                }
            }
        },
        created() {
            this.getList();
            this.getRoleList();
        },
        methods: {
            // 获取用户列表
            getList() {
                this.loading = true;
                const params = {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    user_name: this.searchForm.user_name,
                    real_name: this.searchForm.real_name
                };
                
                axios.get('/user/list', { params }).then(response => {
                    this.loading = false;
                    if (response.data.code === 200) {
                        const data = response.data.data;
                        this.userList = data.list;
                        this.total = data.total;
                    } else {
                        this.$message.error(response.data.msg);
                    }
                }).catch(() => {
                    this.loading = false;
                    this.$message.error('获取用户列表失败');
                });
            },
            // 获取角色列表
            getRoleList() {
                axios.get('/role/available').then(response => {
                    console.log('获取可用角色列表响应:', response);
                    if (response.data.code === 200) {
                        this.roleList = response.data.data || [];
                        console.log('可用角色列表:', this.roleList);
                    } else {
                        this.$message.error(response.data.msg || '获取角色列表失败');
                    }
                }).catch(error => {
                    console.error('获取角色列表错误:', error);
                    if (error.response) {
                        console.error('错误响应:', error.response);
                        this.$message.error(error.response.data?.msg || '获取角色列表失败，请重试');
                    } else {
                        this.$message.error('网络错误，请重试');
                    }
                });
            },
            // 处理搜索
            handleSearch() {
                this.pageNum = 1;
                this.getList();
            },
            // 重置搜索
            resetSearch() {
                this.searchForm = {
                    user_name: '',
                    real_name: ''
                };
                this.handleSearch();
            },
            // 处理分页大小变化
            handleSizeChange(val) {
                this.pageSize = val;
                this.getList();
            },
            // 处理页码变化
            handleCurrentChange(val) {
                this.pageNum = val;
                this.getList();
            },
            // 打开分配角色对话框
            handleAssignRole(row) {
                if (!row || !row.user_id) {
                    this.$message.error('用户信息无效');
                    return;
                }

                console.log('准备分配角色，当前用户:', row);
                this.currentUser = row;
                this.dialogVisible = true;
                this.roleForm.roleIds = []; // 清空之前的选择

                // 获取用户当前角色
                axios.get(`/role/user/${row.user_id}`).then(response => {
                    console.log('获取用户角色响应:', response);
                    if (response.data.code === 200) {
                        const roles = response.data.data || [];
                        console.log('用户当前角色列表:', roles);
                        this.roleForm.roleIds = roles.map(role => role.roleId);
                    } else {
                        this.$message.error(response.data.msg || '获取用户角色失败');
                    }
                }).catch(error => {
                    console.error('获取用户角色错误:', error);
                    if (error.response) {
                        console.error('错误响应:', error.response);
                        this.$message.error(error.response.data?.msg || '获取用户角色失败，请重试');
                    } else {
                        this.$message.error('网络错误，请重试');
                    }
                });

                // 获取所有可用角色
                this.getRoleList();
            },
            // 保存用户角色
            saveUserRoles() {
                if (!this.currentUser || !this.currentUser.user_id) {
                    this.$message.error('用户信息无效');
                    return;
                }

                console.log('准备保存角色，当前用户:', this.currentUser);
                console.log('选中的角色IDs:', this.roleForm.roleIds);
                
                this.saveLoading = true;
                const params = new URLSearchParams();
                params.append('userId', this.currentUser.user_id);
                if (this.roleForm.roleIds && this.roleForm.roleIds.length > 0) {
                    this.roleForm.roleIds.forEach(roleId => {
                        params.append('roleIds', roleId);
                    });
                }

                axios.post('/role/user/save', params, {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                }).then(response => {
                    this.saveLoading = false;
                    console.log('保存角色响应:', response);
                    if (response.data.code === 200) {
                        this.$message.success('角色分配成功');
                        this.dialogVisible = false;
                        // 重新加载用户列表和角色信息
                        this.getList();
                        this.getRoleList();
                    } else {
                        this.$message.error(response.data.msg || '保存失败');
                    }
                }).catch(error => {
                    this.saveLoading = false;
                    console.error('保存角色错误:', error);
                    if (error.response) {
                        console.error('错误响应:', error.response);
                        this.$message.error(error.response.data?.msg || '保存失败，请重试');
                    } else {
                        this.$message.error('网络错误，请重试');
                    }
                });
            }
        }
    });
</script>
</body>
</html> 